﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI.WebControls;
using Cms.Application.Admin.Presenters;
using Cms.Application.Admin.Views;
using Cms.Domain;
using Cms.Web.Framework.Controls;
using iLib.Web.UI;

namespace Cms.Web.UI.Admin
{
    public partial class EditMediaFile : AdminPage, IEditMediaFileView
    {
        private EditMediaFilePresenter _presenter;
        
        private int CurrentLocaleId
        {
            get { return int.Parse(ViewState["CurrentLocaleId"].ToString()); }
            set { ViewState["CurrentLocaleId"] = value; }
        }

        #region IEditMediaFileView Members

        public int FileID
        {
            get { return QueryString.GetInt32ID("id"); }
        }

        public void RemoveFileFromOutputCache(string virtualPath)
        {
            HttpContext.Current.Cache.Insert(virtualPath, "remove", null, DateTime.Now.AddDays(-1), TimeSpan.Zero);
        }

        public string ContextTranslationFile
        {
            get { return "Admin/Translations/EditMediaFile.xml"; }
        }
        
        public void SetFolders(string domain, IEnumerable<MediaFolder> folders)
        {
            ddlFolders.Items.Add(new ListItem(domain, "-1"));
            SetFolderTree(1, folders);
        }
        
        public int SelectedFolderID
        {
            get { return int.Parse(ddlFolders.SelectedValue); }
            set { ddlFolders.SelectedValue = value.ToString(); }
        }
        
        public string Name
        {
            get { return txtFilename.Text; }
            set { txtFilename.Text = value; }
        }
        
        public void SetCategories(IList<Category> rootCategories, IList<Category> inheritedCategories,
                                  IList<Category> categories)
        {
            csCategories.SetCategories(rootCategories, inheritedCategories, categories);
            trCategories.Visible = rootCategories.Count > 0;
        }
        
        public IEnumerable<Category> GetSelectedCategories()
        {
            return csCategories.GetSelectedCategories();
        }
        
        public string SortKey
        {
            get { return txtSortKey.Text; }
            set { txtSortKey.Text = value; }
        }
        
        public void SetLocales(IEnumerable<Locale> locales)
        {
            ddlLocales.Items.Clear();
            foreach (Locale l in locales)
                ddlLocales.Items.Add(new ListItem(l.GetTranslation(Localization).Name, l.ID.ToString()));
        }
        
        public int SelectedLocaleID
        {
            get { return CurrentLocaleId; }
            set
            {
                ddlLocales.SelectedValue = value.ToString();
                CurrentLocaleId = value;
            }
        }
        
        public string FileTitle
        {
            get { return txtTitle.Text; }
            set { txtTitle.Text = value; }
        }
        
        public string FileDescription
        {
            get { return txtDescription.Text; }
            set { txtDescription.Text = value; }
        }

        public void SetAllowedAdministratorGroups(IList<AdministratorGroup> availableGroups,
                                                  IList<AdministratorGroup> inheritedGroups,
                                                  IList<AdministratorGroup> groups)
        {
            gsAllowedAdministratorGroups.SetGroups(availableGroups, inheritedGroups, groups);
            trAllowedAdministratorGroups.Visible = availableGroups.Count > 0;
        }
        
        public IEnumerable<AdministratorGroup> GetSelectedAllowedAdministratorGroups()
        {
            return gsAllowedAdministratorGroups.GetSelectedGroups();
        }
        
        public void SetDeniedAdministratorGroups(IList<AdministratorGroup> availableGroups,
                                                 IList<AdministratorGroup> inheritedGroups,
                                                 IList<AdministratorGroup> groups)
        {
            gsDeniedAdministratorGroups.SetGroups(availableGroups, inheritedGroups, groups);
            trDeniedAdministratorGroups.Visible = availableGroups.Count > 0;
        }
        
        public IEnumerable<AdministratorGroup> GetSelectedDeniedAdministratorGroups()
        {
            return gsDeniedAdministratorGroups.GetSelectedGroups();
        }
        
        public void SetRequiredUserGroups(IList<UserGroup> availableGroups, IList<UserGroup> inheritedGroups,
                                          IList<UserGroup> selectedGroups, IList<UserGroup> deselectedGroups)
        {
            gsRequiredUserGroups.SetGroups(availableGroups, inheritedGroups, selectedGroups, deselectedGroups);
            trRequiredUserGroups.Visible = availableGroups.Count > 0;
        }
        
        public IEnumerable<UserGroup> GetSelectedRequiredUserGroups()
        {
            return gsRequiredUserGroups.GetSelectedGroups();
        }
        
        public IEnumerable<UserGroup> GetDeselectedUserGroups()
        {
            return gsRequiredUserGroups.GetDeselectedGroups();
        }

        #endregion

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (FileID < 0)
                Response.Redirect("Media.aspx");
            _presenter = new EditMediaFilePresenter(this);
            int selectedLocaleIndex = ddlLocales.SelectedIndex;
            _presenter.UpdateLocales();
            ddlLocales.SelectedIndex = selectedLocaleIndex;
            if (!Page.IsPostBack)
            {
                _presenter.Initialize();
                HeadingIcon = litIcon.Text;
                hlCancel.NavigateUrl = "Admin/Media.aspx";
                if (!string.IsNullOrEmpty(Request.QueryString["browseitemdata"]))
                    hlCancel.NavigateUrl += "?browseitemdata=" + Server.UrlEncode(Request.QueryString["browseitemdata"]);
            }
            HeadingText = GetText(this, "EditFileHeading");
            tiProperties.OnClientClick = GetClientClickScript(tiProperties);
            tiDescription.OnClientClick = GetClientClickScript(tiDescription);
            ddlLocales.Attributes.Add("onchange",
                                      "if (isDirty()) { " +
                                      "return cms.Dialogs.Confirm(" +
                                      "function (status) { " +
                                      "document.getElementById('ctl00_tabs_hidSave').value = status; " +
                                      "__doPostBack('ctl00$body$ddlLocales',''); " +
                                      "}, " +
                                      "'" + GetText(this, "SaveInfoHeader") + "', " +
                                      "'" + GetText(this, "OptionalSaveInfoMessage") + "', " +
                                      "'" + GetText(this, "SaveInfoOK") + "', " +
                                      "'" + GetText(this, "SaveInfoCancel") + "', " +
                                      "true, " +
                                      "null" +
                                      "); } " +
                                      "else { " +
                                      "document.getElementById('ctl00_tabs_hidSave').value = 'cancel'; " +
                                      "__doPostBack('ctl00$body$ddlLocales',''); " +
                                      "}");
        }

        private string GetClientClickScript(AdminTabItem ti)
        {
            return "cms.Edit.ShowTabOverlays(); " +
                   "if (isDirty()) { " +
                   " return cms.Dialogs.ConfirmLinkButton(this, " +
                   "function (status) { " +
                   "document.getElementById('ctl00_tabs_hidSave').value = status; " +
                   "__doPostBack('" + ti.UniqueID + "$" + ti.ID + "',''); " +
                   "}, " +
                   "'" + GetText(this, "SaveInfoHeader") + "', " +
                   "'" + GetText(this, "OptionalSaveInfoMessage") + "', " +
                   "'" + GetText(this, "SaveInfoOK") + "', " +
                   "'" + GetText(this, "SaveInfoCancel") + "', " +
                   "true, " +
                   "null" +
                   "); } " +
                   "else { " +
                   "document.getElementById('ctl00_tabs_hidSave').value = 'cancel'; " +
                   "}";
        }

        protected override void OnPreRenderComplete(EventArgs e)
        {
            base.OnPreRenderComplete(e);
            if (tabStrip.CurrentValue != tabStrip.SelectedValue && hidSave.Value != "ok")
                _presenter.RefreshProperties();
            upnlProperties.Update();
            ClientScriptProxy.Current.RegisterStartupScript(tabStrip, GetType(),
                                                            "updatePanels",
                                                            "updatePanels('" + tabStrip.SelectedValue + "');", true);
        }
        
        protected void tabStrip_Click(string value)
        {
            if (hidSave.Value == "ok")
                _presenter.Save();
            if (_presenter.IsValid)
                ClientScriptProxy.Current.RegisterStartupScript(tabStrip, GetType(), "init", "init();", true);
            upnlProperties.Update();
            upnlDescription.Update();
            upnlTabs.Update();
        }
        
        protected void ddlFolders_IndexChanged(object sender, EventArgs e)
        {
            _presenter.UpdateCategoriesAndGroups();
            upnlProperties.Update();
        }
        
        protected void ddlLocales_IndexChanged(object sender, EventArgs e)
        {
            if (hidSave.Value == "ok")
                _presenter.Save();
            if (_presenter.IsValid)
            {
                ClientScriptProxy.Current.RegisterStartupScript(tabStrip, GetType(), "init", "init();", true);
            }
            CurrentLocaleId = int.Parse(ddlLocales.SelectedValue);
            _presenter.SaveSelectedLocale();
            _presenter.RefreshProperties();
            upnlDescription.Update();
            upnlProperties.Update();
            upnlTabs.Update();
        }
        
        protected void lbSaveFile_Click(object sender, EventArgs e)
        {
            _presenter.Save();
            if (!_presenter.IsValid)
                return;
            string redirectUrl = "Media.aspx";
            if (!string.IsNullOrEmpty(Request.QueryString["browseitemdata"]))
                redirectUrl += "?browseitemdata=" + Server.UrlEncode(Request.QueryString["browseitemdata"]);
            Response.Redirect(redirectUrl);
        }

        private void SetFolderTree(int level, IEnumerable<MediaFolder> folders)
        {
            foreach (MediaFolder f in folders)
            {
                string name = f.Name;
                for (int i = 0; i < level; i++)
                    name = "&nbsp;&nbsp;&nbsp;&nbsp;" + name;
                ddlFolders.Items.Add(new ListItem(name, f.ID.ToString()));
                SetFolderTree(level + 1, f.SubFolders);
            }
        }
    }
}